package com.payment.web.controller.system;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.alibaba.fastjson.JSONObject;
import com.payment.common.annotation.Log;
import com.payment.common.base.AjaxResult;
import com.payment.common.enums.BusinessType;
import com.payment.common.page.TableDataInfo;
import com.payment.common.type.LevelStatus;
import com.payment.common.type.MerchantUpgradeType;
import com.payment.common.utils.ExcelUtil;
import com.payment.common.utils.StringUtils;
import com.payment.framework.util.ShiroUtils;
import com.payment.framework.web.base.BaseController;
import com.payment.system.domain.Acq;
import com.payment.system.domain.Merchant;
import com.payment.system.domain.MerchantImage;
import com.payment.system.domain.MerchantUpgrade;
import com.payment.system.mapper.AcqMapper;
import com.payment.system.service.IIssBankService;
import com.payment.system.service.IMerchantImageService;
import com.payment.system.service.IMerchantService;
import com.payment.system.service.IMerchantUpgradeService;
import com.payment.system.service.ISysUserService;
import com.payment.system.util.GuangGuUtil;

import net.sf.json.JSONArray;

/**
 * 商户 信息操作处理
 *
 * @author payment
 * @date 2018-12-27
 */
@Controller
@RequestMapping("/system/merchant")
public class MerchantController extends BaseController {

    private static final Logger logger = LoggerFactory.getLogger(MerchantController.class);

    private String prefix = "system/merchant";
    @Autowired
    private IMerchantImageService merchantImageService;
    @Autowired
    private IMerchantService merchantService;
    @Autowired
    private IIssBankService issBankService;
    @Autowired
    private ISysUserService userService;
    @Autowired
    private AcqMapper acqMapper;
    @Autowired
    private IMerchantUpgradeService merchantUpgradeService;


    @RequiresPermissions("system:merchant:view")
    @GetMapping()
    public String merchant(ModelMap mmap) {
        Long userId = ShiroUtils.getUserId();
        String roleKey = userService.selectUserRoleKey(userId);
        mmap.put("role", roleKey);
        return prefix + "/merchant";
    }

    /**
     * 查询商户列表
     */
    @RequiresPermissions("system:merchant:list")
    @PostMapping("/list")
    @ResponseBody
    public TableDataInfo list(Merchant merchant) {
        startPage();
        List<Merchant> list = merchantService.selectMerchantList(merchant);
        return getDataTable(list);
    }


    /**
     * 导出商户列表
     */
    @RequiresPermissions("system:merchant:export")
    @PostMapping("/export")
    @ResponseBody
    public AjaxResult export(Merchant merchant) {
        List<Merchant> list = merchantService.selectMerchantList(merchant);
        ExcelUtil<Merchant> util = new ExcelUtil<Merchant>(Merchant.class);
        return util.exportExcel(list, "我的客户");
    }

    /**
     * 新增商户
     */
    @GetMapping("/add")
    public String add() {
        return prefix + "/add";
    }

    /**
     * 新增保存商户
     */
    @RequiresPermissions("system:merchant:add")
    @Log(title = "商户", businessType = BusinessType.INSERT)
    @PostMapping("/add")
    @ResponseBody
    public AjaxResult addSave(Merchant merchant) {
        return toAjax(merchantService.insertMerchant(merchant));
    }

    /**
     * 修改商户
     */
    @GetMapping("/edit/{iD}")
    public String edit(@PathVariable("iD") String iD, ModelMap mmap) {
        Merchant merchant = merchantService.selectMerchantById(iD);
        mmap.put("issBank", issBankService.selectIssBankAll());
        mmap.put("merchant", merchant);
        return prefix + "/edit";
    }

    /**
     * 修改保存商户
     */
    @RequiresPermissions("system:merchant:edit")
    @Log(title = "商户", businessType = BusinessType.UPDATE)
    @PostMapping("/edit")
    @ResponseBody
    public AjaxResult editSave(Merchant merchant) {

        MerchantUpgrade merchantUpgrade = new MerchantUpgrade();
        merchantUpgrade.setLevel(merchant.getLevel());
        merchantUpgrade.setMerchantId(merchant.getId());
        List<MerchantUpgrade> list = merchantUpgradeService.selectMerchantUpgradeList(merchantUpgrade);
        Merchant merchant1 = merchantService.selectMerchantById(merchant.getId());
        if (list == null || list.size() == 0) {
            merchantUpgrade.setPhone(merchant1.getPhone());
            merchantUpgrade.setMerchantName(merchant1.getMerchantCnName());
            merchantUpgrade.setId(StringUtils.randomUUID());
            merchantUpgrade.setType(MerchantUpgradeType.MANUAL.getCode());
            merchantUpgradeService.insertMerchantUpgrade(merchantUpgrade);
        }


        return toAjax(merchantService.updateMerchant(merchant));
    }

    /**
     * 修改保存商户信息
     */
    @RequiresPermissions("system:merchant:edit")
    @Log(title = "商户", businessType = BusinessType.UPDATE)
    @PostMapping("/editMerchant")
    @ResponseBody
    public AjaxResult editMerchant(Merchant merchant) {
        return toAjax(merchantService.updateMerchant(merchant));
    }

    /**
     * 禁用或者启用
     */
    @PostMapping("/updateUseStatusById")
    @ResponseBody
    public AjaxResult updateUseStatusById(String id) {
        return merchantService.updateUseStatusById(id);
    }

    /**
     * 修改商户角色
     */
    @GetMapping("/editRole/{iD}")
    public String updateRole(@PathVariable("iD") String iD, ModelMap mmap) {
        Merchant merchant = merchantService.selectMerchantById(iD);
        mmap.put("merchant", merchant);
        return prefix + "/editRole";
    }


    /**
     * 修改限额
     */
    @GetMapping("/editQuota/{iD}")
    public String editQuota(@PathVariable("iD") String iD, ModelMap mmap) {
        Merchant merchant = merchantService.selectMerchantById(iD);
        mmap.put("merchant", merchant);
        return prefix + "/editQuota";
    }


    /**
     * 商户详情
     * 根据商户id
     */
    @GetMapping("/detail/{iD}")
    public String detail(@PathVariable("iD") String iD, ModelMap mmap) {
        List<MerchantImage> merchantImageList = merchantImageService.selectMerchantImageListByMerchantId(iD);
        if (merchantImageList != null) {
            for (MerchantImage image : merchantImageList) {
                image.setImageUrl(image.getImageUrl());
            }
        }
        mmap.put("merchantImage", merchantImageList);
        mmap.put("merchant", merchantService.selectMerchantByIdDeDensity(iD));
        return prefix + "/detail";
    }

    //自动补全商户名称
    @PostMapping("/autosearch")
    @ResponseBody
    public List<String> autosearch(String name) {
        List<String> list = merchantService.selectNameByAutosearch(name);
        return list;
    }


    //客户关系  直推 间推
    @GetMapping("/customerRelation/{phone}")
    public String customerRelation(@PathVariable("phone") String phone, ModelMap mmap) {
        mmap.put("phone", phone);
        return prefix + "/customerRelation";
    }

    @GetMapping("/merchantUpgrade/{id}")
    public String merchantUpgrade(@PathVariable("id") String id, ModelMap mmap) {
        mmap.put("id", id);
        return prefix + "/merchantUpgrade";
    }

    /**
     * 客户关系列表： 直推或者间推
     *
     * @param
     * @return
     */
    @PostMapping("/customerRelationList")
    @ResponseBody
    public TableDataInfo customerRelationList(Merchant merchant) {
        startPage();
        List<Merchant> list = merchantService.selectMerchantList(merchant);
        return getDataTable(list);
    }

    //上级关系
    @GetMapping("/superiorRelation/{phone}")
    public String superiorRelation(@PathVariable("phone") String phone, ModelMap mmap) {
        mmap.put("phone", phone);
        return prefix + "/superiorRelation";
    }

    @PostMapping("/superiorRelation")
    @ResponseBody
    public TableDataInfo superiorRelation(String phone) {
        boolean f = true;
        List<Merchant> list = new ArrayList<Merchant>();
        Merchant merchant = merchantService.selectByPhone(phone);
        String parPhone = merchant.getParentPhone();
        while (f) {
            Merchant merchant1 = merchantService.selectByPhone(parPhone);
            if (merchant1 != null) {
                list.add(merchant1);
                if (merchant1.getLevel().equals(LevelStatus.sex.getCode())) {
                    f = false;
                }
            } else {
                break;
            }


            parPhone = merchant1.getParentPhone();
        }
        return getDataTable(list);
    }


    /**
     * 重置支付密码
     */
    @PostMapping("/updatePayPwd")
    @ResponseBody
    public AjaxResult updatePayPwd(String id) {
        if (StringUtils.isEmpty(id)) {
            return AjaxResult.error(1, "获取用户信息失败");
        }
        Merchant merchant1 = new Merchant();
        merchant1.setId(id);
        merchant1.setPaymentPwd("e10adc3949ba59abbe56e057f20f883e");
        int r = merchantService.updateMerchant(merchant1);
        if (r > 0) {
            return AjaxResult.success("重置支付密码成功");
        }
        return AjaxResult.success("重置支付密码失败");
    }


    /**
     * 商户钱包查询
     *
     * @param iD
     * @param mmap
     * @return
     */
    @GetMapping("/findMoneyCj/{iD}")
    public String findMoney(@PathVariable("iD") String iD, ModelMap mmap) {
        //查询商户信息
        Merchant merchant = merchantService.selectMerchantById(iD);
        if (StringUtils.isNotNull(merchant)) {
            try {
                //上送 钱包查询
                JSONObject jsonObject = GuangGuUtil.walletQuery(merchant);
                // wallet":[{"company_id":"1001","balance":"5.0000"},{"company_id":"1003","balance":"0.00"}]
                if (StringUtils.isNotNull(jsonObject)) {
                    if (("SUCCESS").equals(jsonObject.getString("ret_code"))) {
                        if (("YQB000000").equals(jsonObject.getString("res_code"))) {
                            //转化上游返回信息
                            JSONArray jsonArr = JSONArray.fromObject(jsonObject.getString("wallet"));
                            List<Map<String, Object>> list = new ArrayList<Map<String, Object>>();
                            for (int i = 0; i < jsonArr.size(); i++) {
                                Map<String, Object> map = new HashMap<>();
                                String acqCode = jsonArr.getJSONObject(i).get("company_id").toString();
                                String balance = jsonArr.getJSONObject(i).get("balance").toString();
                                Acq acq = acqMapper.selectAcqByCode(acqCode);
                                if (acq != null) {
                                    String acqName = acq.getAcqName();
                                    //公司名称
                                    map.put("acqName", acqName);
                                    //钱包金额
                                    map.put("balance", balance);
                                    list.add(map);
                                }
                            }
                            mmap.put("merchantList", list);
                        }
                    }
                }
            } catch (Exception e) {
                logger.error("钱包查询失败！{}", e);
                mmap.put("merchantList", "");
            }
        } else {
            mmap.put("merchantList", "");
        }
        return prefix + "/findMoneyCj";
    }

    /**
     * 客户关系 推荐数量
     *
     * @param phone
     * @param mmap
     * @return
     */
    @GetMapping("/findNumber/{phone}")
    public String findNumber(@PathVariable("phone") String phone, ModelMap mmap) {
        List<Map<String, Object>> jt = merchantService.selectLevelsCount(phone);
        mmap.put("lists", jt);
        return prefix + "/relations";
    }

    /**
     * 修改上下级
     *
     * @param phone
     * @param mmap
     * @return
     */
    @GetMapping("/findMerchantParent/{phone}")
    public String findMerchantParent(@PathVariable("phone") String phone, ModelMap mmap) {
        Merchant merchant = merchantService.selectByPhone(phone);
        mmap.put("merchant", merchant);
        return prefix + "/updateMerchantParent";
    }


    /**
     * 修改上下级
     *
     * @param merchant
     * @param parPhone 现推荐人手机
     * @return
     */
    @PostMapping("/updateMerchantParent")
    @ResponseBody
    public AjaxResult updateMerchantParent(Merchant merchant, String parPhone) {
        if (StringUtils.isEmpty(parPhone)) {
            return AjaxResult.error(1, "获取用户推荐人失败");
        }
        merchant = merchantService.selectMerchantById(merchant.getId());
        //现上级
        Merchant merchantPar = merchantService.selectByPhone(parPhone);
        if (StringUtils.isNull(merchantPar)) {
            return AjaxResult.error(1, "这是个什么？！");
        }
        String merchantPhone = merchant.getPhone();
        if (merchant.getParentPhone().equals(parPhone)) {
            return AjaxResult.error(1, "现上级手机号是原上级手机号！");
        }
        if (merchantPhone.equals(parPhone)) {
            return AjaxResult.error(1, "这是个什么？！！现上级手机号是该商户商户手机号");
        }
        if (merchantPhone.equals(merchantPar.getParentPhone())) {
            return AjaxResult.error(1, "这是个什么？！！【" + merchantPar.getMerchantCnName() + "】的上级是" + merchant.getMerchantCnName());
        }
        int r = merchantService.updateMerchantParent(merchantPhone, parPhone);
        if (r > 0) {
            return AjaxResult.success("修改成功");
        } else {
            return AjaxResult.error("修改失败");
        }
    }

}